import React, { FC, ReactText, useRef, useState } from 'react';
import { getMessage } from '@inbiz/react';
import { Cascader, Tag } from 'antd';
import { MultipleCascaderProps } from 'rc-cascader';
import classNames from 'classnames';
import { IOptionType, TargetLevelProps } from '../../type';
import './style.less';

interface IProps extends Partial<Omit<MultipleCascaderProps, 'options' | 'onChange'>> {
  className?: string;
  dropdownClassName?: string;
  options: IOptionType[];
  placeholder?: string;
  value?: ReactText[][];
  targetLevel?: TargetLevelProps;
  labelMap: { [p: string]: string[] };
  showCheckedStrategy: 'SHOW_PARENT' | 'SHOW_CHILD';
  onChange?: (v: ReactText[][], vOptions: IOptionType[]) => void;
}

const MultipleView: FC<IProps> = ({
  className,
  dropdownClassName,
  options,
  placeholder,
  value,
  targetLevel,
  labelMap,
  showCheckedStrategy,
  onChange,
  ...restProps
}) => {
  const onPreventMouseDown: React.MouseEventHandler<HTMLSpanElement> = (event) => {
    event.preventDefault();
    event.stopPropagation();
  };


  return (
    <Cascader
      {...restProps}
      showCheckedStrategy={Cascader[showCheckedStrategy]}
      multiple
      allowClear={false}
      placeholder={placeholder}
      maxTagCount="responsive"
      options={options}
      value={value}
      className={classNames(className, `${className}-multiple`)}
      dropdownClassName={classNames(`${dropdownClassName} ${options.length < 1 ? 'empty' : ''}`, {
        [`${className}-multiple-dropdown-leaf`]: targetLevel === 'leaf',
      })}
      onChange={onChange}
      tagRender={({ onClose, closable, label }) => {
        const labelValue = labelMap[label as string];

        return (
          <Tag
            closable={closable}
            onClose={onClose}
            onMouseDown={onPreventMouseDown}
            className={`${className}-multiple-tag`}
          >
            {Array.isArray(labelValue) ? [...labelValue].pop() : label}
          </Tag>
        );
      }}
      notFoundContent={getMessage('Cascader.notFoundContent')}
    />
  );
};

export default MultipleView;
